package com.miao.websecurity.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.cors.CorsUtils;

import javax.annotation.Resource;

/**
 * @author MiaoWenqing
 * @escription: SpringSecurity 配置类
 * @date 2021/1/16 15:58
 */
@Configuration
public class WebSecurityConfig  extends WebSecurityConfigurerAdapter {




    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and().headers().cacheControl();
        http.exceptionHandling().accessDeniedHandler(new AccessDeniedHandlerImpl()).authenticationEntryPoint(new AuthenticationEntryPointImpl());
        http.authorizeRequests().requestMatchers(CorsUtils::isPreFlightRequest).permitAll();
        //拦截所有请求
        http.authorizeRequests()
                .antMatchers("/login","/druid/**","/shop/**","/common/**","/admin/store/apply","/admin/resetPassword").permitAll()
                .anyRequest().access("@authService.hasPermission(request,authentication)");
        http.addFilter(new AuthenticationFilter(authenticationManager()));
        http.addFilterAfter(new AuthorizationFilter() , AuthenticationFilter.class);



    }




    @Bean(value = "myPasswordEncoder")
    public PasswordEncoder getPasswordEncoder(){
        return new BCryptPasswordEncoder();
    }




}
